package com.ruoyi.system.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.domain.SysDept;
import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.system.api.model.LoginUser;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.mapper.*;
import com.ruoyi.system.vo.req.BatchTaskReqVO;
import com.ruoyi.system.vo.req.QuestionAnswerReqVO;
import com.ruoyi.system.vo.req.TaskCheckDetailReqVO;
import com.ruoyi.system.vo.req.TaskDetailReqVO;
import com.ruoyi.system.vo.resp.QuestionAnswerRespVO;
import com.ruoyi.system.vo.resp.TaskReqDTO;
import com.ruoyi.system.vo.resp.TaskRespDTO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.service.IFkwzTaskService;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * 任务检查Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-06-04
 */
@Service
public class FkwzTaskServiceImpl implements IFkwzTaskService 
{
    @Autowired
    private FkwzTaskMapper taskMapper;

    @Autowired
    private SysDeptMapper deptMapper;

    @Autowired
    private FkwzServiceFileMapper fileMapper;

    @Autowired
    private FkwzTaskCheckDetailMapper taskCheckDetailMapper;

    @Autowired
    private FkwzUserQuestionAnswerMapper questionAnswerMapper;

    @Autowired
    private FkwzTaskFollowLogsMapper taskFollowLogsMapper;


    /**
     * 查询任务检查
     * 
     * @param taskId 任务检查主键
     * @return 任务检查
     */
    @Override
    public TaskRespDTO selectFkwzTaskByTaskId(Long taskId)
    {
        TaskRespDTO taskRespDTO = taskMapper.selectFkwzTaskByTaskId(taskId);

        if (Objects.nonNull(taskRespDTO)) {
             int allStandard = Objects.nonNull(taskRespDTO.getStandard()) && Objects.nonNull(taskRespDTO.getNotStandard()) ? taskRespDTO.getStandard() + taskRespDTO.getNotStandard() : 0;
            taskRespDTO.setAllStandard( allStandard);
            List<QuestionAnswerRespVO> list = questionAnswerMapper.selectQuestionAnswerList(taskRespDTO.getTaskId());
//             List<FkwzUserQuestionAnswer> userQuestionAnswers = questionAnswerMapper.selectList(new LambdaQueryWrapper<FkwzUserQuestionAnswer>()
//                     .eq(FkwzUserQuestionAnswer::getChenkTaskId, taskRespDTO.getTaskId()).eq(FkwzUserQuestionAnswer::getStatus, 0));
            if (!list.isEmpty()) {
                list.stream().forEach(i -> {
                    i.setStandardOrNotName(0 == i.getStandardOrNot() ? "达标" : "不达标");
                    if (StringUtils.isNotBlank(i.getLackItem())){
                        i.setLackItemList(Arrays.asList(i.getLackItem().split(",")));
                    }
                });
            }
            taskRespDTO.setQuestionAnswerList(list);

            List<FkwzServiceFile> fileList = fileMapper.selectList(new LambdaQueryWrapper<FkwzServiceFile>()
                    .eq(FkwzServiceFile::getBusinessId, taskRespDTO.getTaskId())
                    .eq(FkwzServiceFile::getBusinessType, 0).eq(FkwzServiceFile::getStatus, 0));
            taskRespDTO.setFileList(fileList);

            //todo 后期需要加上让任务日志

        }
        return taskRespDTO;
    }

    /**
     * 查询任务检查列表
     * 
     * @param fkwzTask 任务检查
     * @return 任务检查
     */
    @Override
    public List<TaskRespDTO> selectFkwzTaskList(TaskReqDTO fkwzTask)
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUser.getSysUser();
        return taskMapper.selectFkwzTaskList(fkwzTask,sysUser);
    }

    /**
     * 新增任务检查
     * 
     * @param fkwzTask 任务检查
     * @return 结果
     */
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    @Override
    public int insertFkwzTask(FkwzTask fkwzTask)
    {
        fkwzTask.setCreateTime(DateUtils.getNowDate());
        fkwzTask.setCreateOprUserid(SecurityUtils.getUserId());
        fkwzTask.setUpdateTime(new Date());
        fkwzTask.setUpdateOprUserid(SecurityUtils.getUserId());
        return taskMapper.insertFkwzTask(fkwzTask);
    }

    /**
     * 修改任务检查
     * 
     * @param fkwzTask 任务检查
     * @return 结果
     */
    @Override
    public int updateFkwzTask(FkwzTask fkwzTask)
    {
        fkwzTask.setUpdateTime(DateUtils.getNowDate());
        fkwzTask.setUpdateOprUserid(SecurityUtils.getUserId());
        return taskMapper.updateFkwzTask(fkwzTask);
    }

    /**
     * 批量删除任务检查
     * 
     * @param taskIds 需要删除的任务检查主键
     * @return 结果
     */
    @Override
    public int deleteFkwzTaskByTaskIds(Long[] taskIds)
    {
        int i = 0;
        for (Long taskId : taskIds) {
             FkwzTask fkwzTask = new FkwzTask();
            fkwzTask.setTaskId(taskId);
            fkwzTask.setStatus(1);
            fkwzTask.setUpdateTime(new Date());
            fkwzTask.setUpdateOprUserid(SecurityUtils.getUserId());
              i += taskMapper.updateFkwzTask(fkwzTask);
        }
        return i;
    }

    /**
     * 删除任务检查信息
     * 
     * @param taskId 任务检查主键
     * @return 结果
     */
    @Override
    public int deleteFkwzTaskByTaskId(Long taskId)
    {
        return taskMapper.deleteFkwzTaskByTaskId(taskId);
    }


    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    @Override
    public int insertBatchFkwzTask(BatchTaskReqVO vo) {

        SysUser sysUser = SecurityUtils.getLoginUser().getSysUser();
        SysDept dept = deptMapper.selectDeptById(sysUser.getDeptId());

        int autotaskSource = (dept.getStreetId() != null && dept.getZoneId() != null) ? 2 : dept.getCityId() != null ? 1 : dept.getProvinceId() != null ? 0 : null;
        int i = 0;
        List<FkwzTask> taskList = vo.getTaskList();
        for (FkwzTask fkwzTask : taskList) {
            fkwzTask.setCreateTime(DateUtils.getNowDate());
            fkwzTask.setCreateOprUserid(SecurityUtils.getUserId());
            fkwzTask.setUpdateTime(new Date());
            fkwzTask.setUpdateOprUserid(SecurityUtils.getUserId());
//            fkwzTask.setProvinceId(dept.getProvinceId());
//            fkwzTask.setCityId(dept.getCityId());
//            fkwzTask.setZoneId(dept.getZoneId());
//            fkwzTask.setStreetId(dept.getStreetId());
            fkwzTask.setLastDate(vo.getLastDate());
            fkwzTask.setRemark(vo.getRemark());
            fkwzTask.setTaskSource(Objects.nonNull(fkwzTask.getTaskSource()) ?fkwzTask.getTaskSource():autotaskSource);
            fkwzTask.setTaskStatus(0);
              i = taskMapper.insertFkwzTask(fkwzTask);
        }
        return i;
    }



    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    @Override
    public void addOrUpdateTaskDetail(TaskCheckDetailReqVO reqVO) {
        TaskDetailReqVO taskDetailReqVO = reqVO.getTaskDetailReqVO();

        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUser.getSysUser();

        List<QuestionAnswerReqVO> answerItemList = reqVO.getAnswerItemList();
        Map<Integer, List<QuestionAnswerReqVO>> groupMap = answerItemList
                .stream().collect(Collectors.groupingBy(QuestionAnswerReqVO::getStandardOrNot));
        //任务检查详情
        int notStandard = Objects.nonNull(groupMap.get(1)) ? groupMap.get(1).size() : 0;
        int checkStatus = (0 == notStandard) ? 0 : 1;

        if (Objects.nonNull(taskDetailReqVO.getTaskId())){
            FkwzTask taskCheckDetail = new FkwzTask();
            taskCheckDetail.setCheckUserId(sysUser.getUserId());
            taskCheckDetail.setStandard(Objects.nonNull(groupMap.get(0)) ? groupMap.get(0).size() : 0);
            taskCheckDetail.setNotStandard(notStandard);
            taskCheckDetail.setUpdateBy(sysUser.getUserId().toString());
            taskCheckDetail.setUpdateTime(new Date());
            taskCheckDetail.setCheckStatus(checkStatus );
            taskCheckDetail.setTaskId(taskDetailReqVO.getTaskId());
            taskMapper.updateFkwzTask(taskCheckDetail);
            //问卷重新新增
            answerItemInsert(sysUser, answerItemList, taskCheckDetail);
            //文件重新上传
            fileUpload(reqVO, taskCheckDetail);
        }else {
            FkwzTask addTaskCheckDetail = new FkwzTask();
//        FkwzTaskCheckDetail taskCheckDetail = new FkwzTaskCheckDetail();
            BeanUtils.copyProperties(taskDetailReqVO, addTaskCheckDetail);
            addTaskCheckDetail.setCheckUserId(sysUser.getUserId());
            addTaskCheckDetail.setStandard(Objects.nonNull(groupMap.get(0)) ? groupMap.get(0).size() : 0);
            addTaskCheckDetail.setNotStandard(notStandard);
            addTaskCheckDetail.setCreateBy(sysUser.getUserId().toString());
            addTaskCheckDetail.setUpdateBy(sysUser.getUserId().toString());
            addTaskCheckDetail.setCreateTime(new Date());
            addTaskCheckDetail.setUpdateTime(new Date());
            addTaskCheckDetail.setCheckStatus(checkStatus );
            addTaskCheckDetail.setTaskSource(0);
            taskMapper.insert(addTaskCheckDetail);
            //检查明细
            answerItemInsert(sysUser, answerItemList, addTaskCheckDetail);
            //现场照片
            fileUpload(reqVO, addTaskCheckDetail);
        }


        //跟踪日志
//         FkwzTaskFollowLogs FkwzTaskFollowLogs = new FkwzTaskFollowLogs();
//        FkwzTaskFollowLogs.setTaskId(taskCheckDetail.getTaskId());
//        FkwzTaskFollowLogs.setFollowStatus();
        //fileMapper
    }

    private void answerItemInsert(SysUser sysUser, List<QuestionAnswerReqVO> answerItemList, FkwzTask taskCheckDetail) {

        List<FkwzUserQuestionAnswer> fkwzUserQuestionAnswers = questionAnswerMapper
                .selectList(new LambdaQueryWrapper<FkwzUserQuestionAnswer>().eq(FkwzUserQuestionAnswer::getStatus, 0)
                        .eq(FkwzUserQuestionAnswer::getChenkTaskId, taskCheckDetail.getTaskId()));
        if (CollectionUtil.isNotEmpty(fkwzUserQuestionAnswers)) {
            FkwzUserQuestionAnswer questionAnswer = new FkwzUserQuestionAnswer();
            questionAnswer.setStatus(1);
            questionAnswer.setUpdateBy(sysUser.getUserId().toString());
            questionAnswer.setUpdateTime(new Date());
            questionAnswerMapper
                    .update(questionAnswer, new LambdaQueryWrapper<FkwzUserQuestionAnswer>().eq(FkwzUserQuestionAnswer::getStatus, 0)
                            .eq(FkwzUserQuestionAnswer::getChenkTaskId, taskCheckDetail.getTaskId()));
        }
        answerItemList.stream().forEach(reqAnswer -> {
            FkwzUserQuestionAnswer questionAnswer = new FkwzUserQuestionAnswer();
            BeanUtils.copyProperties(reqAnswer, questionAnswer);
            List<String> lackItemList = reqAnswer.getLackItemList();
            if (CollectionUtil.isNotEmpty(lackItemList)){
                String lackItem = lackItemList.stream().collect(Collectors.joining(","));
                questionAnswer.setLackItem(lackItem);
            }
            questionAnswer.setChenkTaskId(taskCheckDetail.getTaskId());
            questionAnswer.setCreateBy(sysUser.getUserId().toString());
            questionAnswer.setUpdateBy(sysUser.getUserId().toString());
            questionAnswer.setCreateTime(new Date());
            questionAnswer.setUpdateTime(new Date());
            questionAnswerMapper.insert(questionAnswer);
        });
    }

    private void fileUpload(TaskCheckDetailReqVO reqVO, FkwzTask taskCheckDetail) {

        List<FkwzServiceFile> fileVos = reqVO.getFileVos();
        if (!fileVos.isEmpty()){
             List<FkwzServiceFile> fileList = fileMapper.selectList(new LambdaQueryWrapper<FkwzServiceFile>()
                    .eq(FkwzServiceFile::getBusinessId, taskCheckDetail.getTaskId())
                    .eq(FkwzServiceFile::getStatus, 0).eq(FkwzServiceFile::getBusinessType, 0));

             if (CollectionUtil.isNotEmpty(fileList)){
                  FkwzServiceFile fkwzServiceFile = new FkwzServiceFile();
                 fkwzServiceFile.setStatus(1);
                 fkwzServiceFile.setBusinessId(taskCheckDetail.getTaskId());
                 fileMapper.update(fkwzServiceFile,new LambdaQueryWrapper<FkwzServiceFile>()
                         .eq(FkwzServiceFile::getBusinessId, taskCheckDetail.getTaskId())
                         .eq(FkwzServiceFile::getStatus, 0).eq(FkwzServiceFile::getBusinessType, 0));
             }

            fileVos.stream().forEach(fileVo ->{
                fileVo.setBusinessType(0);
                fileVo.setBusinessId(taskCheckDetail.getTaskId());
                fileMapper.insertFkwzServiceFile(fileVo);
            });
        }
    }




    /**
     * 查询任务检查列表
     *
     * @param fkwzTask 任务检查
     * @return 任务检查
     */
    @Override
    public List<TaskRespDTO> checkRecordList(TaskReqDTO fkwzTask)
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUser.getSysUser();
        return taskMapper.checkRecordList(fkwzTask,sysUser);
    }

    @Override
    public Object checkRecordCount(TaskReqDTO fkwzTask) {
        Map<String, Integer> map = new HashMap<>();
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUser.getSysUser();
        List<TaskRespDTO> taskRespDTOS = taskMapper.checkRecordList(fkwzTask, sysUser);
        if (CollectionUtil.isEmpty(taskRespDTOS)) return map;
        map.put("allData",taskRespDTOS.size());
        taskRespDTOS.removeIf(task -> task.getCheckStatus() == null);
        Map<Integer, List<TaskRespDTO>> groupMap = taskRespDTOS.stream().collect(Collectors.groupingBy(TaskRespDTO::getCheckStatus));
//        处置状态：0-无需处置，1-处置中，2-已处置
        List<TaskRespDTO> taskRespDTOS1 = groupMap.get(0);
        List<TaskRespDTO> taskRespDTOS2 = groupMap.get(1);
        List<TaskRespDTO> taskRespDTOS3 = groupMap.get(2);
        map.put("noDisposal", Objects.nonNull(taskRespDTOS1) ? taskRespDTOS1.size() : 0);//无需处置noDisposal
        map.put("atDisposal", Objects.nonNull(taskRespDTOS2) ? taskRespDTOS2.size() : 0);//处置中 atDisposal
        map.put("disposed", Objects.nonNull(taskRespDTOS3) ? taskRespDTOS3.size() : 0);//已处置 disposed
        return map;
    }

    @Override
    public Object checkStatusCount(TaskReqDTO fkwzTask) {
        Map<String, Integer> map = new HashMap<>();
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUser.getSysUser();
        List<TaskRespDTO> taskRespDTOS = taskMapper.selectFkwzTaskList(fkwzTask, sysUser);
        if (taskRespDTOS.isEmpty())  return map;
        Map<Integer, List<TaskRespDTO>> groupMap = taskRespDTOS.stream().collect(Collectors.groupingBy(TaskRespDTO::getTaskStatus));
        List<TaskRespDTO> taskRespDTOS1 = groupMap.get(0);
        List<TaskRespDTO> taskRespDTOS2 = groupMap.get(1);
        map.put("notInspect", Objects.nonNull(taskRespDTOS1) ? taskRespDTOS1.size() : 0);//待检查notInspect
        map.put("inspected", Objects.nonNull(taskRespDTOS2) ? taskRespDTOS2.size() : 0);//已检查  inspected
        map.put("allData", taskRespDTOS.size());// 全部 allData
        return map;
    }

    @Override
    public List<TaskRespDTO> selectWarnList(TaskReqDTO fkwzTask) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUser.getSysUser();
         List<TaskRespDTO> taskRespDTOS = taskMapper.selectWarnList(fkwzTask, sysUser);
        return taskRespDTOS;
    }


}
